﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using AndreasJohansson.Win32.Shell;
using IWshRuntimeLibrary;
using File = System.IO.File;

namespace Toolbar
{
    public class ToolbarForm : Form
    {
        private IContainer components;

        public ToolbarForm()
        {
            //
            // Required for Windows Form Designer support
            //
            InitializeComponent();
            //
            // TODO: Add any constructor code after InitializeComponent call
            //
            m_UsbDriveNotificator.DriveConnected += MUsbDriveNotificatorOnDriveConnected;
            m_UsbDriveNotificator.DriveDisconnected += MUsbDriveNotificatorOnDriveDisconnected;
            //CanFocus = false;
        }

        private void MUsbDriveNotificatorOnDriveDisconnected()
        {
            Invoke((Action) Reload);
        }

        private void MUsbDriveNotificatorOnDriveConnected(string s)
        {
            Invoke((Action)Reload);
        }

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose(disposing);
        }

        private void OnLoad(object sender1, EventArgs e)
        {
            var args = Environment.GetCommandLineArgs();

            var folderPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            for (int index = 0; index < args.Length; index++)
            {
                var arg = args[index].ToLower();
                switch (arg)
                {
                    case "-p":
                        if (Directory.Exists(args[index + 1]))
                        {
                            folderPath = args[index + 1];
                        }
                        else
                        {
                            Console.Out.WriteLine("Directory not found");
                        }
                        index++;
                        break;
                    case "-e":
                        var edge = args[index + 1].ToLower();
                        if (edge.StartsWith("t"))
                        {
                            m_Edge = AppBarEdge.Top;
                        }
                        else if (edge.StartsWith("l"))
                        {
                            m_Edge = AppBarEdge.Left;
                        }
                        else if (edge.StartsWith("r"))
                        {
                            m_Edge = AppBarEdge.Right;
                        }
                        else if (edge.StartsWith("b"))
                        {
                            m_Edge = AppBarEdge.Bottom;
                        }
                        else
                        {
                            Console.Out.WriteLine("Invalid edge");
                        }
                        index++;
                        break;
                    case "-w":
                        var width = args[index + 1].ToLower();
                        if (StartsWith(width, "s", "1"))
                        {
                            m_Columns = 1;
                        }
                        else if (StartsWith(width, "d", "2"))
                        {
                            m_Columns = 1;
                        }
                        else if (StartsWith(width, "t", "3"))
                        {
                            m_Columns = 1;
                        }
                        else
                        {
                            Console.Out.WriteLine("Invalid width");
                        }
                        index++;
                        break;
                    case "-a":
                        if (StartsWith(args[index + 1], "y", "on", "e"))
                        {
                            TopMost = true;
                        }
                        else if (StartsWith(args[index + 1], "n", "of", "d"))
                        {
                            TopMost = false;
                        }
                        else
                        {
                            Console.Out.WriteLine("Invalid top most");
                        }
                        index++;
                        break;
                    case "-i":
                        if (StartsWith(args[index + 1], "s"))
                        {
                            SetSmallIconSize();
                        }
                        else if (StartsWith(args[index + 1], "l"))
                        {
                            SetLargeIconSize();
                        }
                        else
                        {
                            Console.Out.WriteLine("Invalid icon size");
                        }
                        index++;
                        break;
                    case "-n":
                        m_LinksFileName = args[index + 1];

                        index++;
                        break;
                }
            }


            LoadPath(folderPath);
            RegisterBar();
        }

        private static bool StartsWith(string target, params string[] values)
        {
            target = target.ToLower();
            return values.Any(value => target.StartsWith(value));
        }

        private void OnContextMenuStrip1OnOpening(object sende, CancelEventArgs args)
        {
            var cursorPosition = Cursor.Position;
            var clientPosition = PointToClient(cursorPosition);
            var selectedItem = toolStrip1.GetItemAt(clientPosition);
            if (selectedItem != null)
            {
                var file = (string)selectedItem.Tag;
                if (file != null)
                {
                    args.Cancel = true;
                    m_ContextMenu.ShowContextMenu(Handle, new[] { new FileInfo(file) }, cursorPosition);
                    return;
                }
            }

            bottomToolStripMenuItem.Checked = false;
            leftToolStripMenuItem.Checked = false;
            rightToolStripMenuItem.Checked = false;
            topToolStripMenuItem.Checked = false;

            switch (m_Edge)
            {
                case AppBarEdge.Bottom:
                    {
                        bottomToolStripMenuItem.Checked = true;
                        break;
                    }
                case AppBarEdge.Left:
                    {
                        leftToolStripMenuItem.Checked = true;
                        break;
                    }
                case AppBarEdge.Right:
                    {
                        rightToolStripMenuItem.Checked = true;
                        break;
                    }
                case AppBarEdge.Top:
                    {
                        topToolStripMenuItem.Checked = true;
                        break;
                    }

            }
            singleToolStripMenuItem.Checked = false;
            doubleToolStripMenuItem.Checked = false;
            tripleToolStripMenuItem.Checked = false;
            switch (m_Columns)
            {
                case 1:
                    singleToolStripMenuItem.Checked = true;
                    break;
                case 2:
                    doubleToolStripMenuItem.Checked = true;
                    break;
                case 3:
                    tripleToolStripMenuItem.Checked = true;
                    break;
            }
            smallToolStripMenuItem.Checked = false;
            largeToolStripMenuItem.Checked = false;
            if (m_Size.Width == 16)
            {
                smallToolStripMenuItem.Checked = true;

            }
            else
            {
                largeToolStripMenuItem.Checked = true;
            }


            alwaysOnTopToolStripMenuItem.Checked = TopMost;

            var startUpLink = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Startup), m_LinksFileName + ".lnk");

            runAtSystemStartToolStripMenuItem.Checked = File.Exists(startUpLink);

        }

        private void OnClosing(object sender, CancelEventArgs e)
        {
            RegisterBar();
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ToolbarForm));
            this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
            this.chooseFolderToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.positionToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.topToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.leftToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.rightToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.bottomToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.widthToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.singleToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.doubleToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.tripleToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.iconSizeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.smallToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.largeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.alwaysOnTopToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.runAtSystemStartToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
            this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.folderBrowserDialog1 = new System.Windows.Forms.FolderBrowserDialog();
            this.fileSystemWatcher1 = new System.IO.FileSystemWatcher();
            this.toolStrip1 = new Toolbar.ToolStripEx();
            this.toolStripButton1 = new System.Windows.Forms.ToolStripButton();
            this.toolStripButton2 = new System.Windows.Forms.ToolStripButton();
            this.toolStripButton3 = new System.Windows.Forms.ToolStripButton();
            this.toolStripButton4 = new System.Windows.Forms.ToolStripButton();
            this.toolStripButton5 = new System.Windows.Forms.ToolStripButton();
            this.toolStripButton6 = new System.Windows.Forms.ToolStripButton();
            this.contextMenuStrip1.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.fileSystemWatcher1)).BeginInit();
            this.toolStrip1.SuspendLayout();
            this.SuspendLayout();
            // 
            // contextMenuStrip1
            // 
            this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.chooseFolderToolStripMenuItem,
            this.positionToolStripMenuItem,
            this.widthToolStripMenuItem,
            this.iconSizeToolStripMenuItem,
            this.alwaysOnTopToolStripMenuItem,
            this.runAtSystemStartToolStripMenuItem,
            this.toolStripSeparator1,
            this.exitToolStripMenuItem});
            this.contextMenuStrip1.Name = "contextMenuStrip1";
            this.contextMenuStrip1.Size = new System.Drawing.Size(175, 164);
            this.contextMenuStrip1.Opening += new System.ComponentModel.CancelEventHandler(this.OnContextMenuStrip1OnOpening);
            // 
            // chooseFolderToolStripMenuItem
            // 
            this.chooseFolderToolStripMenuItem.Name = "chooseFolderToolStripMenuItem";
            this.chooseFolderToolStripMenuItem.Size = new System.Drawing.Size(174, 22);
            this.chooseFolderToolStripMenuItem.Text = "Choose folder";
            this.chooseFolderToolStripMenuItem.Click += new System.EventHandler(this.chooseFolderToolStripMenuItem_Click);
            // 
            // positionToolStripMenuItem
            // 
            this.positionToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.topToolStripMenuItem,
            this.leftToolStripMenuItem,
            this.rightToolStripMenuItem,
            this.bottomToolStripMenuItem});
            this.positionToolStripMenuItem.Name = "positionToolStripMenuItem";
            this.positionToolStripMenuItem.Size = new System.Drawing.Size(174, 22);
            this.positionToolStripMenuItem.Text = "Edge";
            // 
            // topToolStripMenuItem
            // 
            this.topToolStripMenuItem.Name = "topToolStripMenuItem";
            this.topToolStripMenuItem.Size = new System.Drawing.Size(114, 22);
            this.topToolStripMenuItem.Text = "Top";
            this.topToolStripMenuItem.Click += new System.EventHandler(this.topToolStripMenuItem_Click);
            // 
            // leftToolStripMenuItem
            // 
            this.leftToolStripMenuItem.Name = "leftToolStripMenuItem";
            this.leftToolStripMenuItem.Size = new System.Drawing.Size(114, 22);
            this.leftToolStripMenuItem.Text = "Left";
            this.leftToolStripMenuItem.Click += new System.EventHandler(this.leftToolStripMenuItem_Click);
            // 
            // rightToolStripMenuItem
            // 
            this.rightToolStripMenuItem.Name = "rightToolStripMenuItem";
            this.rightToolStripMenuItem.Size = new System.Drawing.Size(114, 22);
            this.rightToolStripMenuItem.Text = "Right";
            this.rightToolStripMenuItem.Click += new System.EventHandler(this.rightToolStripMenuItem_Click);
            // 
            // bottomToolStripMenuItem
            // 
            this.bottomToolStripMenuItem.Name = "bottomToolStripMenuItem";
            this.bottomToolStripMenuItem.Size = new System.Drawing.Size(114, 22);
            this.bottomToolStripMenuItem.Text = "Bottom";
            this.bottomToolStripMenuItem.Click += new System.EventHandler(this.bottomToolStripMenuItem_Click);
            // 
            // widthToolStripMenuItem
            // 
            this.widthToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.singleToolStripMenuItem,
            this.doubleToolStripMenuItem,
            this.tripleToolStripMenuItem});
            this.widthToolStripMenuItem.Name = "widthToolStripMenuItem";
            this.widthToolStripMenuItem.Size = new System.Drawing.Size(174, 22);
            this.widthToolStripMenuItem.Text = "Width";
            this.widthToolStripMenuItem.Visible = false;
            // 
            // singleToolStripMenuItem
            // 
            this.singleToolStripMenuItem.Name = "singleToolStripMenuItem";
            this.singleToolStripMenuItem.Size = new System.Drawing.Size(112, 22);
            this.singleToolStripMenuItem.Text = "Single";
            this.singleToolStripMenuItem.Click += new System.EventHandler(this.singleToolStripMenuItem_Click);
            // 
            // doubleToolStripMenuItem
            // 
            this.doubleToolStripMenuItem.Name = "doubleToolStripMenuItem";
            this.doubleToolStripMenuItem.Size = new System.Drawing.Size(112, 22);
            this.doubleToolStripMenuItem.Text = "Double";
            this.doubleToolStripMenuItem.Click += new System.EventHandler(this.doubleToolStripMenuItem_Click);
            // 
            // tripleToolStripMenuItem
            // 
            this.tripleToolStripMenuItem.Name = "tripleToolStripMenuItem";
            this.tripleToolStripMenuItem.Size = new System.Drawing.Size(112, 22);
            this.tripleToolStripMenuItem.Text = "Triple";
            this.tripleToolStripMenuItem.Click += new System.EventHandler(this.thribleToolStripMenuItem_Click);
            // 
            // iconSizeToolStripMenuItem
            // 
            this.iconSizeToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.smallToolStripMenuItem,
            this.largeToolStripMenuItem});
            this.iconSizeToolStripMenuItem.Name = "iconSizeToolStripMenuItem";
            this.iconSizeToolStripMenuItem.Size = new System.Drawing.Size(174, 22);
            this.iconSizeToolStripMenuItem.Text = "Icon size";
            // 
            // smallToolStripMenuItem
            // 
            this.smallToolStripMenuItem.Name = "smallToolStripMenuItem";
            this.smallToolStripMenuItem.Size = new System.Drawing.Size(103, 22);
            this.smallToolStripMenuItem.Text = "Small";
            this.smallToolStripMenuItem.Click += new System.EventHandler(this.smallToolStripMenuItem_Click);
            // 
            // largeToolStripMenuItem
            // 
            this.largeToolStripMenuItem.Name = "largeToolStripMenuItem";
            this.largeToolStripMenuItem.Size = new System.Drawing.Size(103, 22);
            this.largeToolStripMenuItem.Text = "Large";
            this.largeToolStripMenuItem.Click += new System.EventHandler(this.largeToolStripMenuItem_Click);
            // 
            // alwaysOnTopToolStripMenuItem
            // 
            this.alwaysOnTopToolStripMenuItem.Name = "alwaysOnTopToolStripMenuItem";
            this.alwaysOnTopToolStripMenuItem.Size = new System.Drawing.Size(174, 22);
            this.alwaysOnTopToolStripMenuItem.Text = "Always on top";
            this.alwaysOnTopToolStripMenuItem.Click += new System.EventHandler(this.alwaysOnTopToolStripMenuItem_Click);
            // 
            // runAtSystemStartToolStripMenuItem
            // 
            this.runAtSystemStartToolStripMenuItem.Name = "runAtSystemStartToolStripMenuItem";
            this.runAtSystemStartToolStripMenuItem.Size = new System.Drawing.Size(174, 22);
            this.runAtSystemStartToolStripMenuItem.Text = "Run at system start";
            this.runAtSystemStartToolStripMenuItem.Click += new System.EventHandler(this.runAtSystemStartToolStripMenuItem_Click);
            // 
            // toolStripSeparator1
            // 
            this.toolStripSeparator1.Name = "toolStripSeparator1";
            this.toolStripSeparator1.Size = new System.Drawing.Size(171, 6);
            // 
            // exitToolStripMenuItem
            // 
            this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
            this.exitToolStripMenuItem.Size = new System.Drawing.Size(174, 22);
            this.exitToolStripMenuItem.Text = "Exit";
            this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
            // 
            // folderBrowserDialog1
            // 
            this.folderBrowserDialog1.ShowNewFolderButton = false;
            // 
            // fileSystemWatcher1
            // 
            this.fileSystemWatcher1.EnableRaisingEvents = true;
            this.fileSystemWatcher1.NotifyFilter = ((System.IO.NotifyFilters)((System.IO.NotifyFilters.FileName | System.IO.NotifyFilters.DirectoryName)));
            this.fileSystemWatcher1.SynchronizingObject = this;
            this.fileSystemWatcher1.Renamed += new System.IO.RenamedEventHandler(this.fileSystemWatcher1_Renamed);
            this.fileSystemWatcher1.Deleted += new System.IO.FileSystemEventHandler(this.fileSystemWatcher1_Deleted);
            this.fileSystemWatcher1.Created += new System.IO.FileSystemEventHandler(this.fileSystemWatcher1_Created);
            this.fileSystemWatcher1.Changed += new System.IO.FileSystemEventHandler(this.fileSystemWatcher1_Changed);
            // 
            // toolStrip1
            // 
            this.toolStrip1.AllowItemReorder = true;
            this.toolStrip1.ContextMenuStrip = this.contextMenuStrip1;
            this.toolStrip1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.toolStrip1.ImageScalingSize = new System.Drawing.Size(32, 32);
            this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.toolStripButton1,
            this.toolStripButton2,
            this.toolStripButton3,
            this.toolStripButton4,
            this.toolStripButton5,
            this.toolStripButton6});
            this.toolStrip1.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.VerticalStackWithOverflow;
            this.toolStrip1.Location = new System.Drawing.Point(0, 0);
            this.toolStrip1.Name = "toolStrip1";
            this.toolStrip1.Padding = new System.Windows.Forms.Padding(3);
            this.toolStrip1.Size = new System.Drawing.Size(76, 284);
            this.toolStrip1.TabIndex = 1;
            this.toolStrip1.Text = "toolStrip1";
            // 
            // toolStripButton1
            // 
            this.toolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            this.toolStripButton1.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton1.Image")));
            this.toolStripButton1.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.toolStripButton1.Name = "toolStripButton1";
            this.toolStripButton1.Size = new System.Drawing.Size(69, 36);
            this.toolStripButton1.Text = "toolStripButton1";
            // 
            // toolStripButton2
            // 
            this.toolStripButton2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            this.toolStripButton2.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton2.Image")));
            this.toolStripButton2.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.toolStripButton2.Name = "toolStripButton2";
            this.toolStripButton2.Size = new System.Drawing.Size(69, 36);
            this.toolStripButton2.Text = "toolStripButton2";
            // 
            // toolStripButton3
            // 
            this.toolStripButton3.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            this.toolStripButton3.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton3.Image")));
            this.toolStripButton3.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.toolStripButton3.Name = "toolStripButton3";
            this.toolStripButton3.Size = new System.Drawing.Size(69, 36);
            this.toolStripButton3.Text = "toolStripButton3";
            // 
            // toolStripButton4
            // 
            this.toolStripButton4.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            this.toolStripButton4.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton4.Image")));
            this.toolStripButton4.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.toolStripButton4.Name = "toolStripButton4";
            this.toolStripButton4.Size = new System.Drawing.Size(69, 36);
            this.toolStripButton4.Text = "toolStripButton4";
            // 
            // toolStripButton5
            // 
            this.toolStripButton5.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            this.toolStripButton5.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton5.Image")));
            this.toolStripButton5.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.toolStripButton5.Name = "toolStripButton5";
            this.toolStripButton5.Size = new System.Drawing.Size(69, 36);
            this.toolStripButton5.Text = "toolStripButton5";
            // 
            // toolStripButton6
            // 
            this.toolStripButton6.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            this.toolStripButton6.Image = ((System.Drawing.Image)(resources.GetObject("toolStripButton6.Image")));
            this.toolStripButton6.ImageTransparentColor = System.Drawing.Color.Magenta;
            this.toolStripButton6.Name = "toolStripButton6";
            this.toolStripButton6.Size = new System.Drawing.Size(69, 36);
            this.toolStripButton6.Text = "toolStripButton6";
            // 
            // ToolbarForm
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(76, 284);
            this.Controls.Add(this.toolStrip1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
            this.Name = "ToolbarForm";
            this.Text = "AppBar";
            this.Load += new System.EventHandler(this.OnLoad);
            this.Closing += new System.ComponentModel.CancelEventHandler(this.OnClosing);
            this.contextMenuStrip1.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.fileSystemWatcher1)).EndInit();
            this.toolStrip1.ResumeLayout(false);
            this.toolStrip1.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        #region APPBAR

        private bool m_BarRegistered;
        private ContextMenuStrip contextMenuStrip1;
        private ToolStripMenuItem chooseFolderToolStripMenuItem;
        private FolderBrowserDialog folderBrowserDialog1;
        private ToolStripEx toolStrip1;
        private ToolStripButton toolStripButton1;
        private ToolStripMenuItem exitToolStripMenuItem;
        private ToolStripButton toolStripButton2;
        private ToolStripButton toolStripButton3;
        private ToolStripButton toolStripButton4;
        private ToolStripButton toolStripButton5;
        private ToolStripButton toolStripButton6;
        private int m_CallBack;
        private ToolStripMenuItem positionToolStripMenuItem;
        private ToolStripMenuItem topToolStripMenuItem;
        private ToolStripMenuItem leftToolStripMenuItem;
        private ToolStripMenuItem rightToolStripMenuItem;
        private ToolStripMenuItem bottomToolStripMenuItem;
        private readonly ShellContextMenu m_ContextMenu = new ShellContextMenu();
        private AppBarEdge m_Edge = AppBarEdge.Right;
        private ToolStripSeparator toolStripSeparator1;
        private ToolStripMenuItem widthToolStripMenuItem;
        private ToolStripMenuItem singleToolStripMenuItem;
        private ToolStripMenuItem doubleToolStripMenuItem;
        private ToolStripMenuItem tripleToolStripMenuItem;
        private Size m_Size = new Size(32, 32);
        private ToolStripMenuItem alwaysOnTopToolStripMenuItem;
        private ToolStripMenuItem iconSizeToolStripMenuItem;
        private ToolStripMenuItem smallToolStripMenuItem;
        private ToolStripMenuItem largeToolStripMenuItem;
        private int m_Columns = 1;
        private ToolStripMenuItem runAtSystemStartToolStripMenuItem;
        private string m_Path;
        private static string DefaultLinksFileName = "Toolbar";
        private FileSystemWatcher fileSystemWatcher1;
        private string m_LinksFileName = DefaultLinksFileName;
        private BrowseForFolder m_FolderBrowse = new BrowseForFolder();
        private UsbDriveNotificator m_UsbDriveNotificator = new UsbDriveNotificator();

        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.Style &= (~0x00C00000); // WS_CAPTION
                cp.Style &= (~0x00800000); // WS_BORDER
                //                cp.Style = 96040000;
                cp.ExStyle = 0x00000080;// | 0x00000008; // WS_EX_TOOLWINDOW | WS_EX_TOPMOST
                //cp.ExStyle = 00000180;
                return cp;
            }
        }

        [DllImport("SHELL32", CallingConvention = CallingConvention.StdCall)]
        private static extern uint SHAppBarMessage(int dwMessage, ref AppBarData pData);


        [DllImport("User32.dll", ExactSpelling = true,
            CharSet = CharSet.Auto)]
        private static extern bool MoveWindow
            (IntPtr hWnd, int x, int y, int cx, int cy, bool repaint);

        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        private static extern int RegisterWindowMessage(string msg);

        private void RegisterBar()
        {
            var barData = new AppBarData
            {
                cbSize = Marshal.SizeOf(typeof(AppBarData)),
                hWnd = Handle,
                uCallbackMessage = CallBack
            };

            if (!m_BarRegistered)
            {

                SHAppBarMessage((int)AppBarMsg.New, ref barData);
                m_BarRegistered = true;

                AppBarSetPosition();
            }
            else
            {
                SHAppBarMessage((int)AppBarMsg.Remove, ref barData);
                m_BarRegistered = false;
            }
        }

        private int CallBack
        {
            get
            {
                if (m_CallBack == 0)
                {
                    m_CallBack = RegisterWindowMessage(Guid.NewGuid().ToString());
                }
                if (m_CallBack == 0)
                {
                    int lastWin32Error = Marshal.GetHRForLastWin32Error();
                    Marshal.ThrowExceptionForHR(lastWin32Error);
                }
                return m_CallBack;
            }
        }

        private void AppBarSetPosition()
        {
            var appBarData = new AppBarData
            {
                cbSize = Marshal.SizeOf(typeof(AppBarData)),
                hWnd = Handle,
                uEdge = (int)m_Edge,
                uCallbackMessage = CallBack
            };

            var width = m_Size.Width * m_Columns + 4 * m_Columns + toolStrip1.Padding.Left * m_Columns + toolStrip1.Padding.Right * m_Columns;
            var height = m_Size.Height * m_Columns + 4 * m_Columns + toolStrip1.Padding.Top * m_Columns + toolStrip1.Padding.Bottom * m_Columns;
            if (appBarData.uEdge == (int)AppBarEdge.Left || appBarData.uEdge == (int)AppBarEdge.Right)
            {
                toolStrip1.LayoutStyle = ToolStripLayoutStyle.VerticalStackWithOverflow;
                //                toolStrip1.LayoutStyle = ToolStripLayoutStyle.Flow;
                appBarData.rc.top = 0;
                appBarData.rc.bottom = SystemInformation.PrimaryMonitorSize.Height;
                if (appBarData.uEdge == (int)AppBarEdge.Left)
                {
                    appBarData.rc.left = 0;
                    appBarData.rc.right = width;
                }
                else
                {
                    appBarData.rc.right = SystemInformation.PrimaryMonitorSize.Width;
                    appBarData.rc.left = appBarData.rc.right - width;
                }
            }
            else
            {
                toolStrip1.LayoutStyle = ToolStripLayoutStyle.HorizontalStackWithOverflow;
                appBarData.rc.left = 0;
                appBarData.rc.right = SystemInformation.PrimaryMonitorSize.Width;
                if (appBarData.uEdge == (int)AppBarEdge.Top)
                {
                    appBarData.rc.top = 0;
                    appBarData.rc.bottom = height;
                }
                else
                {
                    appBarData.rc.bottom = SystemInformation.PrimaryMonitorSize.Height;
                    appBarData.rc.top = appBarData.rc.bottom - height;
                }
            }

            // Query the system for an approved size and position. 
            SHAppBarMessage((int)AppBarMsg.QueryPosition, ref appBarData);

            //SHAppBarMessage((int)AppBarMsg.SetState, ref appBarData);

            // Adjust the rectangle, depending on the edge to which the 
            // appbar is anchored. 
            switch (appBarData.uEdge)
            {
                case (int)AppBarEdge.Left:
                    appBarData.rc.right = appBarData.rc.left + width;
                    break;
                case (int)AppBarEdge.Right:
                    appBarData.rc.left = appBarData.rc.right - width;
                    break;
                case (int)AppBarEdge.Top:
                    appBarData.rc.bottom = appBarData.rc.top + height;
                    break;
                case (int)AppBarEdge.Bottom:
                    appBarData.rc.top = appBarData.rc.bottom - height;
                    break;
            }

            // Pass the final bounding rectangle to the system. 
            SHAppBarMessage((int)AppBarMsg.SetPosition, ref appBarData);

            // Move and size the appbar so that it conforms to the 
            // bounding rectangle passed to the system. 
            MoveWindow(appBarData.hWnd, appBarData.rc.left, appBarData.rc.top,
                       appBarData.rc.right - appBarData.rc.left, appBarData.rc.bottom - appBarData.rc.top, true);

            SHAppBarMessage((int)AppBarMsg.Activate, ref appBarData);
        }

        protected override void WndProc(ref Message m)
        {
            if (m.Msg == m_CallBack)
            {
                switch (m.WParam.ToInt32())
                {
                    case (int)AppBarNotify.PositionChanged:
                        AppBarSetPosition();
                        break;
                }
            }
            else if (m.Msg == 0x7b)
            {
                Console.Out.WriteLine("m = {0}", m);
            }

            base.WndProc(ref m);
        }

        #endregion

        private void chooseFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string selectFolder = m_FolderBrowse.SelectFolder("Choose folder", Environment.GetFolderPath(Environment.SpecialFolder.Desktop), this);
//            folderBrowserDialog1.RootFolder = Environment.SpecialFolder.MyComputer;
  //          var result = folderBrowserDialog1.ShowDialog();
    //        if (result == DialogResult.OK)
            {
                if (selectFolder != null)
                {
                    LoadPath(selectFolder);
                }
//                    folderBrowserDialog1.SelectedPath);
            }
        }
        private void Reload()
        {
            if (m_Path != null)
            {
                LoadPath(m_Path);
            }
            else
            {
                toolStrip1.Items.Clear();
                fileSystemWatcher1.EnableRaisingEvents = false;
                fileSystemWatcher1.Path = "";
            }
        }

        private void LoadPath(string path)
        {
            m_Path = path;
            IEnumerable<string> files;
            switch (path.ToLower())
            {
                case "computer":
                    files = Environment.GetLogicalDrives();
                    break;
                default:
                    files = Directory.GetFiles(m_Path).Union(Directory.GetDirectories(m_Path));
                    break;
            }
            toolStrip1.SuspendLayout();
            toolStrip1.Items.Clear();
            if (Directory.Exists(path))
            {
                fileSystemWatcher1.Path = path;
                fileSystemWatcher1.EnableRaisingEvents = true;
            }


            var maxHeight = 0;
            var maxWidth = 0;


            foreach (var file in files)
            {

                var fileName = Path.GetFileNameWithoutExtension(file);

                Icon icon;

                if (m_Size.Width == 16)
                {
                    icon = ShellIcon.GetSmallIcon(file);
                }
                else
                {
                    icon = ShellIcon.GetLargeIcon(file);
                }

                var bitmap = icon.ToBitmap();
                maxHeight = Math.Max(maxHeight, icon.Height);
                maxWidth = Math.Max(maxWidth, icon.Width);
                var button = new ToolStripButton(fileName)
                                 {
                                     Image = bitmap,
                                     ToolTipText = fileName,
                                     DisplayStyle = ToolStripItemDisplayStyle.Image,
                                     Tag = file,
                                     Size = new Size(m_Size.Width + 4, m_Size.Height + 4),
                                     AutoSize = false,
                                     Margin = new Padding(0),
                                     ImageScaling = ToolStripItemImageScaling.None
                                 };
                var file1 = file;
                MouseEventHandler handler = delegate(object sender, MouseEventArgs args)
                                                          {
                                                              if (args.Button == MouseButtons.Left)
                                                              {
                                                                  //((ToolStripItem) sender).CanSelect = false;
                                                                  ((ToolStripItem)sender).DoDragDrop(sender, DragDropEffects.Move);
                                                              }
                                                          };
                //button.MouseDown += handler;
                //button.MouseMove += handler;
                button.Click +=
                    delegate
                    {
                        try
                        {
                            Process.Start(file1);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                        }
                    };
                toolStrip1.Items.Add(button);

            }
            toolStrip1.ImageScalingSize = new Size(maxWidth, maxHeight);

            toolStrip1.ResumeLayout();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }


        private void topToolStripMenuItem_Click(object sender, EventArgs e)
        {
            m_Edge = AppBarEdge.Top;
            AppBarSetPosition();
        }

        private void leftToolStripMenuItem_Click(object sender, EventArgs e)
        {
            m_Edge = AppBarEdge.Left;
            AppBarSetPosition();
        }

        private void rightToolStripMenuItem_Click(object sender, EventArgs e)
        {
            m_Edge = AppBarEdge.Right;
            AppBarSetPosition();
        }

        private void bottomToolStripMenuItem_Click(object sender, EventArgs e)
        {
            m_Edge = AppBarEdge.Bottom;
            AppBarSetPosition();
        }

        private void singleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            m_Columns = 1;
            AppBarSetPosition();
        }

        private void doubleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            m_Columns = 2;
            AppBarSetPosition();
        }

        private void thribleToolStripMenuItem_Click(object sender, EventArgs e)
        {
            m_Columns = 3;
            AppBarSetPosition();
        }

        private void alwaysOnTopToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TopMost = !TopMost;
        }

        private void smallToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetSmallIconSize();
            Reload();
            AppBarSetPosition();
        }

        private void SetSmallIconSize()
        {
            m_Size = new Size(16, 16);
        }

        private void largeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SetLargeIconSize();
            Reload();
            AppBarSetPosition();
        }

        private void SetLargeIconSize()
        {
            m_Size = new Size(32, 32);
        }

        private void runAtSystemStartToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var startUpLink = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Startup), m_LinksFileName + ".lnk");

            if (File.Exists(startUpLink))
            {
                File.Delete(startUpLink);
            }
            else
            {
                CreateShellLink(
                    Environment.GetFolderPath(Environment.SpecialFolder.Startup),
                    m_LinksFileName + ".lnk",
                    Assembly.GetExecutingAssembly().Location,
                    "-p \"" + m_Path + "\" -e " + m_Edge + " -w " + m_Columns + " -a " + (TopMost ? "yes" : "no") + " -i " +
                    (m_Size.Width == 16 ? "small" : "large") + (m_LinksFileName == DefaultLinksFileName ? "" : " -n \"" + m_LinksFileName + "\""),
                    "Subscribe to and download podcasts",
                    Assembly.GetExecutingAssembly().Location + ", 0");
            }

        }

        static void CreateShellLink(
            string folderName,
            string linkName,
            string linkPath,
            string arguments,
            string description,
            string iconLocation)
        {
            var shell = new WshShell();

            Type type = Type.GetTypeFromProgID("WScript.Shell");
            if (type != null)
            {
                var fso = Activator.CreateInstance(type);
                var shortcut = type.InvokeMember("CreateShortcut", BindingFlags.InvokeMethod, null, fso, new object[] { System.IO.Path.Combine(folderName, linkName) });
                type.InvokeMember("TargetPath", BindingFlags.SetProperty, null, shortcut, new object[] { linkPath });
                type.InvokeMember("Description", BindingFlags.SetProperty, null, shortcut, new object[] { description });
                type.InvokeMember("IconLocation", BindingFlags.SetProperty, null, shortcut, new object[] { iconLocation });
                type.InvokeMember("Arguments", BindingFlags.SetProperty, null, shortcut, new object[] { arguments });
                type.InvokeMember("Save", BindingFlags.InvokeMethod, null, shortcut, new object[] { });

            }
        }

        private void fileSystemWatcher1_Created(object sender, FileSystemEventArgs e)
        {
            Reload();
        }

        private void fileSystemWatcher1_Deleted(object sender, FileSystemEventArgs e)
        {
            Reload();
        }

        private void fileSystemWatcher1_Renamed(object sender, RenamedEventArgs e)
        {
            Reload();
        }

        private void fileSystemWatcher1_Changed(object sender, FileSystemEventArgs e)
        {
            Reload();
        }

    }
}